package com.reny.ll.git.base_logic

import EmptyViewModel
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatDelegate
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.alibaba.android.arouter.launcher.ARouter
import com.gyf.immersionbar.ImmersionBar
import com.gyf.immersionbar.ktx.immersionBar
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.reny.ll.git.core.actTry
import com.reny.ll.git.mvvm.MvvmActivity
import com.reny.ll.git.mvvm.extras.getRString
import org.kodein.di.DIAware
import org.kodein.di.android.closestDI
import org.kodein.di.android.subDI

abstract class MActivity<VB : ViewDataBinding> : MvvmActivity<VB>(), DIAware, IUseEventBus {

    override val di by subDI(closestDI()) {}

    override val delegateImp: MDelegateImp by lazy {
        MDelegateImp(this)
    }

    override val viewModel: MViewModel by viewModels<EmptyViewModel>()

    //val _api: ApiInterface by instance()

    override fun getNoMoreTip(): String? = ""

    open fun isTransStatusBar(): Boolean = false
    open fun darkFont(): Boolean = AppCompatDelegate.getDefaultNightMode() != AppCompatDelegate.MODE_NIGHT_YES

    //open fun useLocalNightMode(): Boolean = true
    open fun statusColor(): Int = R.color.tool_bg

    override fun useEventBus(): Boolean = false

    private var keepScreenOn = false

    private val inputMethodManager by lazy {
        getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    }

    private var fragmentTransaction: FragmentTransaction? = null

    fun isSoftInputShow(): Boolean {
        // 虚拟键盘隐藏 判断view是否为空
        val view = window.peekDecorView()
        if (view != null) {
            return inputMethodManager.isActive && window.currentFocus != null
        }
        return false
    }

    fun hideSoftKeyboard() {
        /*val instrumentation = Instrumentation()
        instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK)*/
        inputMethodManager.hideSoftInputFromWindow(currentFocus?.windowToken, 0)
    }

    var loadingDialog: BasePopupView? = null

    fun cancelProgressDialog() {
        try {
            runOnUiThread {
                loadingDialog?.dismiss()
                loadingDialog?.destroy()
            }
        } catch (e: Exception) {
        }
    }

    protected open fun addFragment(contentId: Int, fragment: Fragment) {
        if (fragmentTransaction == null) {
            fragmentTransaction = supportFragmentManager.beginTransaction()
        }
        fragmentTransaction?.apply {
            if (!fragment.isAdded){
                add(contentId, fragment)
            } else {
                replace(contentId, fragment)
            }
            try {
                commit()
            } catch (e: Exception){
                commitAllowingStateLoss()
            }
        }
    }

    fun keepScreenOn(){
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        keepScreenOn = true
    }

    override fun onBackPressed() {
        onBackPressedDispatcher.onBackPressed()
    }

    override fun onDestroy() {
        super.onDestroy()
        if(keepScreenOn){
            window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        }
    }

}


fun Activity.injectARouter() {
    ARouter.getInstance().inject(this)
}

fun Activity.setStatusBar(isTransStatusBar: Boolean, darkFont: Boolean = true) {
    //val isDarkFont = if(this is MActivity && null != this.darkFont()) this.darkFont()!! else !isDarkMode()
    val isDarkFont = if (this is MActivity<*>) this.darkFont() else darkFont
    val statusColor = if (this is MActivity<*>) statusColor() else R.color.tool_bg

    immersionBar {
        if (isTransStatusBar){
            transparentStatusBar()
        }else{
            fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色
            statusBarColor(statusColor)
        }
        statusBarDarkFont(isDarkFont)
        navigationBarEnable(false) //不修改导航栏颜色
        //navigationBarColor(R.color.white) //导航栏颜色
        //autoNavigationBarDarkModeEnable(true, 0f)
    }
    /*if (isTransStatusBar) {
        ImmersionBar.with(this)
            .transparentStatusBar()
            .statusBarDarkFont(isDarkFont)
            .navigationBarColor(R.color.color_bg_main)
            .init()
    } else {
        ImmersionBar.with(this)
            .fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色
            .statusBarColor(if (this is MActivity<*>) statusColor() else R.color.tool_bg)
            .statusBarDarkFont(isDarkFont)
            .navigationBarColor(R.color.color_bg_main)
            .init()
    }*/

    /*if(this is MActivity && this.useLocalNightMode()){
        setLocalNightMode()
    }*/
}

fun Activity.statusBarDarkFont(isDarkFont: Boolean) {
    ImmersionBar.with(this)
        .statusBarDarkFont(isDarkFont)
        .init()
}

/*
fun AppCompatActivity.setLocalNightMode(){
    if(isDarkMode()){
        this.delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_YES
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
    }else{
        this.delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_NO
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
    }
}*/

fun Any.showLoading(
    msg: String? = null,
    isCancel: Boolean = true,
    activity: Activity? = actTry()
) {
    activity?.let {
        if (activity.isDestroyed) return
        if (activity is MActivity<*>) {
            activity.runOnUiThread {
                activity.loadingDialog = XPopup.Builder(activity)
                    .dismissOnTouchOutside(false)
                    .dismissOnBackPressed(isCancel)
                    .asLoading(msg ?: getRString(R.string.loading_tip))
                    .show()
            }
        }
    }
}

fun Any.hideLoading(
    delay: Long = 50,
    activity: Activity? = actTry()
) {
    activity?.let {
        if (activity.isDestroyed) return
        if (activity is MActivity<*>) {
            activity.runOnUiThread {
                if (delay > 0) {
                    activity.loadingDialog?.delayDismiss(delay)
                } else {
                    activity.loadingDialog?.dismiss()
                }
            }
        }
    }
}
